package com.tuju.jetpackfirstdemo.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.tuju.jetpackfirstdemo.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MyTextSwitchView extends TextSwitcher implements ViewSwitcher.ViewFactory {
    private int index = -1;
    private int intervalTime = 3000; //单位毫秒
    private List<String> mResourceText = new ArrayList<>();
    private Handler mHandler = new Handler();

    public MyTextSwitchView(Context context) {
        super(context);
        init();
    }

    public MyTextSwitchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        this.setFactory(this);
        this.setInAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.in_animation));
        this.setOutAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.out_animation));
    }

    public void addAll(List<String> res) {
        index = 0;
        updateText();
        this.mResourceText.addAll(res);
    }

    public void add(String res) {
        this.mResourceText.add(res);
    }

    public void clear() {
        pause();
        this.mResourceText.clear();
    }

    public void pause() {
        mHandler.removeCallbacksAndMessages(null);
    }

    public void start() {
        setTextStillTime(intervalTime);
    }

    public void resetStar() {
        index = -1;
        setTextStillTime(intervalTime);
    }

    public void setTextStillTime(int time) {
        intervalTime = time;
        mHandler.removeCallbacks(runnable);
        if (!mResourceText.isEmpty()) {
            mHandler.postDelayed(runnable, intervalTime);
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            index = next(); //取得下标值
            updateText();  //更新TextSwitcherd显示内容;
            mHandler.postDelayed(runnable, intervalTime);
        }
    };

    private int next() {
        return (index + 1) % mResourceText.size();
    }

    //切换文字
    private void updateText() {
        if (index < 0 || index >= mResourceText.size()) {
            pause();
        } else {
            this.setText(mResourceText.get(index));
        }
    }

    @Override
    public View makeView() {
        TextView tv = new TextView(getContext());
        return tv;
    }
}
